package com.epoint.pjq.view;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;

import com.epoint.pjq.MyApplication;
import com.epoint.pjq.core.StringHelp;
import com.epoint.pjq.core.crash.LogUtils;
import com.epoint.pjq.core.mqtt.SMP_MQTT_Service;
import com.epoint.pjq.core.service.MusicService;
import com.epoint.pjq.mqtttest.R;

public class Main_Activity extends Activity{

	public static boolean debug = false;
	// 网络相关
	ConnectivityManager manager;

	static String deviceid = "";
	static String isRandomIMEI;
	
	static String deviceidpathname; // 设备ID存放文件夹名称

	public static Intent playservice;
	AlertDialog dialog;
	TextView msg_txt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		initUI();
		initMQTT();
	}
	

	private void initMQTT() {
		// MQTT订阅主题
		String topic 			= String.format(MyApplication.getInstance().getApplicationContext().getString(R.string.topic), getDeviceID(this));
		// MQTT服务地址
		String hosturl 			= getString(R.string.hosturi);
		// MQTT重连时间间隔
		String keepalivetime 	= getString(R.string.keepalivetime);
		// 开启消息接受
		SMP_MQTT_Service.startMqttService(this,topic,hosturl,keepalivetime);
		
		// 动态注册广播接收器：接收MQTT推送消息
		IntentFilter filter = new IntentFilter();
		filter.addAction(SMP_MQTT_Service.ACTION_INTENT_RECEIVER_USERINFO);
		registerReceiver(UserInfoReceiver, filter);
		
		// 动态注册广播接收器：接收MQTT相关日志
		IntentFilter filter2 = new IntentFilter();
		filter2.addAction(SMP_MQTT_Service.ACTION_INTENT_RECEIVER_LOG);
		registerReceiver(mqttLogReceiver, filter2);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			// 显示推送消息
			case 1:
				// 提示语音评价
				playservice.putExtra("filename", R.raw.getmessage);
				startService(Main_Activity.playservice);
				String bs = (String) msg.obj;
				msg_txt.setText(bs);
				break;
			case 2:
			default:
				break;
			}
		}
	};
	
	@Override
	protected void onDestroy() {
		// 注销MQTT相关广播接收器
		unregisterReceiver(UserInfoReceiver);
		unregisterReceiver(mqttLogReceiver);
		super.onDestroy();
	}

	
	/****************************************** 广播接收器:接收MQTT推送消息 ********************************************/
	
	// MQTT:消息接收广播
	BroadcastReceiver UserInfoReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String message = intent.getStringExtra("UserInfoMessage");
			String bs = message;
			Message msg = new Message();
			msg.what = 1;
			msg.obj  = bs;
			handler.sendMessage(msg);
		}
	};
	
	// MQTT:接收日志广播
	BroadcastReceiver mqttLogReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String message = intent.getStringExtra("logMessage");
			Log.i("andli","[MQTT_LOG]:"+message);
		}
	};
	
	/************************************************************** 初始化UI 开始 **************************************************************/
	private void initUI() {
		deviceidpathname = getString(R.string.deviceidpath);
		isRandomIMEI	 = getString(R.string.pj_imei);
		// 启动语音播放Service
		playservice = new Intent(Main_Activity.this, MusicService.class);

		msg_txt = (TextView) findViewById(R.id.msg_txt);
	}
	
	// 播放语音
	public void playMusic(Context con, String filename) {
		try {
			MediaPlayer m = new MediaPlayer();
			AssetFileDescriptor descriptor = con.getAssets().openFd(filename);
			m.setDataSource(descriptor.getFileDescriptor(),descriptor.getStartOffset(), descriptor.getLength());
			descriptor.close();
			m.prepare();
			m.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	/************************************************************** 获取设备标识码 开始 **************************************************************/
	
	public static String getDeviceID(Context con) {
		try {
			if (isRandomIMEI.equals("0")) {
				// 直接获取当前设备的ID
				deviceid = Main_Activity.getDeviceId(con).toLowerCase();
			} else {
				String path = Environment.getExternalStorageDirectory() + "/" + deviceidpathname + "/imei.txt";
				File file = new File(path);
				if (file.exists()) {
					StringBuffer sb = new StringBuffer();
					BufferedReader br = new BufferedReader(new FileReader(file));
					String line = "";
					while ((line = br.readLine()) != null) {
						sb.append(line);
					}
					br.close();
					deviceid = StringHelp.getXMLAtt(sb.toString(), "imei");
				} else {
					if (deviceid == null || deviceid.equals("")) {
						deviceid = getMacInfo(con); // 设备码：网络mac地址
					}
					if (deviceid == null || deviceid.equals("")) {
						deviceid = UUID.randomUUID().toString(); // 设备码：随机生成
					}
					WriteIMEIToSDCard(deviceid);
				}
				deviceid = deviceid.toLowerCase().toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.Log2Storage(e.toString());
		}
		// 标准版测试设备ID
		// deviceid = "20:f4:1b:8f:e6:4d";
		return deviceid;			// 统一转换成小写
	}
	
	public static String getDeviceId(Context con) {
		TelephonyManager tm = (TelephonyManager) con.getSystemService("phone");
		if ((tm.getDeviceId() == null) || ("".equals(tm.getDeviceId()))) {
			return getMacAddress(con);
		}
		return tm.getDeviceId();
	}

	public static String getMacAddress(Context context) {
		try {
			WifiManager wifiManager = (WifiManager) context.getSystemService("wifi");
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			return wifiInfo.getMacAddress();
		} catch (Exception localException) {
		}
		return "";
	}

	// 读取IMEI
	public static String readIMEIToSDCard(String path) {
		File file = new File(path);
		String filestr = file.toString();
		return StringHelp.getXMLAtt(filestr, "imei");
	}

	// 获得MAC地址
	public static String getMacInfo(Context con) {
		String mac;
		WifiManager wifiManager = (WifiManager) con.getSystemService(WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		if (wifiInfo.getMacAddress() != null) {
			mac = wifiInfo.getMacAddress();
		} else {
			mac = "";
		}
		return mac;
	}

	// 将IMEI写入SDCard
	public static void WriteIMEIToSDCard(String imei) {
		try {
			String path = Environment.getExternalStorageDirectory() + "/"+ deviceidpathname;
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(path + "/imei.txt", true)));
			pw.write("<imei>");
			pw.write(imei);
			pw.write("</imei>");
			pw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/************************************************************** 获取设备标识码 结束 **************************************************************/
}
